﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Shinkansen.Core;
using Shinkansen.Web.UI.WebControls;

namespace Shinkansen.Mvc
{
    /// <summary>
    /// Shinkansen for ASP.NET MVC
    /// </summary>
    public static class ShinkansenMvc
    {
        /// <summary>
        /// Processes static resources.
        /// </summary>
        /// <param name="collector">The collector.</param>
        /// <returns></returns>
        public static MvcHtmlString Includes(Action<IResourceCollector> collector)
        {
            return Includes (collector, ShinkansenOptions.Default);
        }

        /// <summary>
        /// Processes static resources.
        /// </summary>
        /// <param name="collector">The collector.</param>
        /// <param name="options">The options.</param>
        /// <returns></returns>
        public static MvcHtmlString Includes(Action<IResourceCollector> collector, ShinkansenOptions options)
        {
            if (collector == null)
                throw new ArgumentNullException ("collector", "The collector delegate may not be null.");

            if (options == null)
                throw new ArgumentNullException ("options", "The 'options' parameter may not be null. You may pass ShinkansenOptions.Default instead.");


            var resources = new ResourceCollector ();
            collector (resources);

            IEnumerable<JavaScriptInclude>  jsResources = resources.JavaScript.Select (js => new JavaScriptInclude (js));
            IEnumerable<CssInclude>         cssResources = resources.Css.Select (css => new CssInclude (css));
            StringBuilder                   markup = new StringBuilder();


            Action<string> registerScriptTag  = tag => markup.Append (tag);
            Action<string> registerCssLink    = tag => markup.Append (tag);

            new JavaScriptTagBuilder (options, jsResources, registerScriptTag).Run ();
            new CssTagBuilder (options, cssResources, registerCssLink).Run ();

            return new MvcHtmlString(markup.ToString());
        }
    }
}
